package com.javasm.pk.controller;

import com.javasm.pk.service.GradeCodeGenerator;
import com.javasm.pk.service.PrimaryKeyService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/pk")
public class PrimaryKeyController {

    @Resource
    private PrimaryKeyService primaryKeyService;

    /**
     * 返回一个基于时间戳的唯一 id
     *
     * @return
     */
    @GetMapping("/getId")
    public long getId() {
        return primaryKeyService.getLongKey();
    }


    /**
     * 返回一个基于数据库和缓存的唯一id
     *
     * @param type 业务类型
     * @return
     */
    @GetMapping("/getLongKey")
    public long getLongKeyInterval(@RequestParam String type) {
        return primaryKeyService.getLongKeyAndInterval(type);
    }

    /**
     * 返回多个基于数据库的唯一id
     *
     * @param type 业务类型
     * @return
     */
    @GetMapping("/getLongRange")
    public List<Long> getLongKeyInterval(@RequestParam String type, @RequestParam int count) {
        return primaryKeyService.getLongRange(type, count);
    }

    /**
     * 返回一个基于数据库的序列号
     *
     * @param type           业务类型
     * @param length（序列号的长度）
     * @return
     */
    @GetMapping("/getSerialNumber")
    public String getSerialNumber(@RequestParam String type, @RequestParam int length) {
        return primaryKeyService.getSerialNumber(type, length);
    }

    /**
     * 返回级次编码
     *
     * @param rule
     * @param parentCode
     * @param type
     * @return
     */
    @GetMapping("/getGradeCode")
    public String getGradeCode(@RequestParam String rule, @RequestParam(required = false) String parentCode,
                               @RequestParam String type) {
        return GradeCodeGenerator.getNextCode(rule, parentCode, type);
    }

}
